package com.jacky.demo.ui;

import android.hardware.Camera;
import android.os.Bundle;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.jacky.demo.BaseActivity;
import com.jacky.demo.R;
import com.jacky.demo.util.ViewUtils;
import com.jacky.demo.widget.CameraPreviewView;

/**
 * Created by lixinquan on 2018/6/4.
 */

public class PreviewActivity extends BaseActivity implements View.OnClickListener {

    CameraPreviewView mCameraPreviewView;
    private boolean isPictureTaking;
    private MyOrientationEventListener orientationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected int getContentView() {
        return R.layout.pre_view_activity;
    }

    @Override
    protected void initCreate() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("相机预览");

        mCameraPreviewView = ViewUtils.findView(this, R.id.preview_camera);
        ViewUtils.findView(this, R.id.back).setOnClickListener(this);
        ViewUtils.findView(this, R.id.iv_carema_switch).setOnClickListener(this);
        ViewUtils.findView(this, R.id.btn_take_picture).setOnClickListener(this);


        if(mCameraPreviewView.getNumberOfCameras() <= 1) {
            findViewById(R.id.iv_carema_switch).setVisibility(View.GONE);
        }

        orientationListener = new MyOrientationEventListener();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back :
                onBackPressed();
                break;
            case R.id.iv_carema_switch :
                mCameraPreviewView.switchCamera();
                break;
            case R.id.btn_take_picture :
                takePicture();
                break;
        }
    }

    private void takePicture() {
        if(isPictureTaking) {
            showToast("图片还在处理中，请稍候...");
            return;
        }
        mCameraPreviewView.takePicture(new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                onPictureTakenInThread(data);
                mCameraPreviewView.startPreview();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        orientationListener.enable();
    }

    @Override
    protected void onPause() {
        super.onPause();
        orientationListener.disable();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        orientationListener = null;
    }

    private void onPictureTakenInThread(final byte[] data) {
        isPictureTaking = true;
//        Observable.create(new ObservableOnSubscribe<File>() {
//            @Override
//            public void subscribe(ObservableEmitter<File> e) throws Exception {
//                if (AppUtils.isNetworkAvailable(getActivity())) {
//                    BitmapFactory.Options options = new BitmapFactory.Options();//防止oom
//                    options.inTempStorage = new byte[100 * 1024];
//                    options.inPreferredConfig = Bitmap.Config.RGB_565;
//                    options.inPurgeable = true;
//                    Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length,options);
//
//                    int rotation = orientationListener.curOrientation;
//                    Logger.d("rotation", rotation);
//                    if (rotation != 0) {
//                        Matrix m = new Matrix();
//                        m.setRotate(rotation, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
//                        Bitmap bm2 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
//                        bm.recycle();
//                        bm = bm2;
//                    }
//                    File file = new File(StorageUtil.getImageDir(),
//                            String.format("xjpz%s.jpg",
//                                    StringUtils.formatCurrentTime("yyyyMMddHHmmssSSS")));
//                    StorageUtil.saveBitmap(file, bm, Bitmap.CompressFormat.JPEG, 80);
//                    bm.recycle();
//                    e.onNext(file);
//                } else {
//                    e.onError(new SocketTimeoutException());
//                }
//                e.onComplete();
//            }
//        })
//                .flatMap(new Function<File, ObservableSource<?>>() {
//                    @Override
//                    public ObservableSource<?> apply(File s) throws Exception {
//                        String md5 = DigestUtils.md5Hex(s);
//                        String time = StringUtils.formatCurrentTime("yyyy-MM-dd_HH:mm:ss");
//                        return HttpClient.create(EvidApi.class).uploadPhotoMD5(
//                                md5, time, locationInfo.getMapType(), s.getName(),
//                                locationInfo.getLatitude(), locationInfo.getLongitude(), locationInfo.getAddrStr());
//                    }
//                })
//                .compose(HttpClient.get())
//                .subscribe(new HttpCallback<JsonObject>() {
//                    @Override
//                    public void onResponse(JsonObject response) {
//                    }
//
//                    @Override
//                    public void onStart() {}
//
//                    @Override
//                    public void onFinish() {
//                        isPictureTaking = false;
//                    }
//                });
    }

    private class MyOrientationEventListener extends OrientationEventListener {

        int curOrientation;
        public MyOrientationEventListener() {
            super(PreviewActivity.this);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            curOrientation = getRotation(orientation);
        }

        private int getRotation(int orientations){
            int rotation;
            if(orientations > 325 || orientations <= 45){
                rotation = mCameraPreviewView.isCameraFacingBack() ? 90 : 270;
            }else if(orientations > 45 && orientations <= 135){
                rotation = 180;
            }else if(orientations > 135 && orientations < 225){
                rotation = mCameraPreviewView.isCameraFacingBack() ? 270 : 90;
            }else {
                rotation = 0;
            }
            return rotation;
        }
    }
}
